//
//  MineCouponsVM.swift
//  LeTu
//
//  Created by g1 on 2023/12/11.
//

import Foundation

enum MineCouponsUseStatus: Int {
    
    case unGet = -1
    case unUse = 0
    case used
    case expire

}

class MineCouponsItemViewModel {
    
    /// 优惠券类型(-1:未领取 0:待使用 1:已使用  2:已过期)
    var useStatus = MineCouponsUseStatus.unGet
    /// 数据分页
    var pageNum = 1
    /// 数据长度
    var pageSize = 20
    /// 列表信息
    var goodsList = [MineCouponsModel]()
    
    /// 获取优惠券列表
    func getCouponList(isLoad: Bool, completeHolder: @escaping NetworkRequestHandle) {
        
        var pageNum = self.pageNum
        pageNum = isLoad ? pageNum + 1 : 1

        var param = [String: Any]()
        
        apiProvider.request(api: useStatus == .unGet ? .getUnUseCoupons(params: [:]):.getCoupons(params: ["useStatus": useStatus.rawValue])) { [weak self] json, jsonArr, code in

            guard let strongSelf = self else { return }

            MYLog("获取优惠券列表：", json)

            var dialog = DialogMessage()

            guard let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHolder(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            guard let data = response.data as? [[String: Any]] else { return completeHolder(dialog) }

            if dialog.code == 200 {

                strongSelf.pageNum = pageNum
                let tempOrderList = Mapper<MineCouponsModel>().mapArray(JSONArray: data)
                if isLoad {
                    strongSelf.goodsList = strongSelf.goodsList + tempOrderList
                } else {
                    strongSelf.goodsList = tempOrderList
                }
                dialog.data = tempOrderList

            }
            completeHolder(dialog)

        } failureHandler: { error in
            completeHolder(DialogMessage())
        }

    }
    
    /// 领取优惠券
    func getCoupon(couponId: Int, completeHandle: @escaping NetworkRequestHandle) {
        
        apiProvider.request(api: .receiveCoupon(couponId: couponId)) { json, jsonArr, code in

            MYLog("领取优惠券", json)
            var dialog = DialogMessage()
            guard code == 200, let respone = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = respone.code
            dialog.message = respone.msg

            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }

    }

}



class MineCouponsVM {
    
    private(set) var titles = ["未领取","待使用","已使用","已过期"]
    
}
